package com.bugbuff.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.bugbuff.dubbo.server.enums.HtTopState;
import com.bugbuff.dubbo.server.enums.HtTotals;
import com.bugbuff.dubbo.server.pojo.Message;
import com.bugbuff.dubbo.server.pojo.Publish;
import com.bugbuff.dubbo.server.pojo.Video;
import com.bugbuff.dubbo.server.vo.PageInfo;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

@Service
@Slf4j
public class MessageApiImpl implements MessageApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Reference
    private QuanZiApi quanZiApi;

    @Reference
    private VideoApi videoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 消息拒绝
     * @param publishId
     * @return
     */
    @Override
    public String rejectMessage(Long userId,String publishId) {
        //saveMessage();
       /* Integer integer = queryAllState(HtTotals.PEOPLE_CHECK);
        System.out.println(integer);*/
        return updateMessageState(userId,publishId,HtTotals.PEOPLE_REJECT);
    }

    /**
     * 消息通过
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public String passMessage(Long userId, String publishId) {

        return updateMessageState(userId,publishId,HtTotals.PEOPLE_PASS);
    }

    /**
     * 消息待审核，提供给外界的方法，视频或动态一开始发布时就会被标记为待审核
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public String checkMessage(Long userId, String publishId) {

        return updateMessageState(userId,publishId,HtTotals.PEOPLE_CHECK);
    }

    /**
     * 消息置顶
     * @param topUserId
     * @param messageId
     * @return
     */
    @Override
    public String top(Long topUserId, String messageId) {

        //TODO 查询redis进行二次取反操作判断

        return updateTopState(topUserId,messageId, HtTopState.STICK);
    }

    /**
     * 消息取消置顶
     * @param topUserId
     * @param messageId
     * @return
     */
    @Override
    public String unTop(Long topUserId, String messageId) {

        //TODO 查询redis进行二次取反操作判断

        return updateTopState(topUserId,messageId,HtTopState.UNSTICK);
    }

    /**
     * 修改置顶状态
     * @param topUserId
     * @param messageId
     * @return
     */
    private String updateTopState(Long topUserId, String messageId,HtTopState htTopState){


        Query query =Query.query(Criteria.where("publishId").is(new ObjectId(messageId)));
        Update update = new Update();
//            update.set("topUserId",topUserId);
        update.set("topState",htTopState.getType());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Message.class);
        if (updateResult.getModifiedCount()>0){
            return messageId;
        }

        return null;
//        return "菜";

    }

    /**
     * 根据消息id查询消息
     * @param messageId
     * @return
     */
    @Override
    public Message getMessageByMessage(String messageId) {

        Query query = Query.query(Criteria.where("id").is(new ObjectId(messageId)));
        Message message = mongoTemplate.findOne(query, Message.class);
        return message;
    }

    /**
     * 根据发布id查询消息
     * @param publishId
     * @return
     */
    public Message getMessageByPublishId(String publishId){

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
        Message message = mongoTemplate.findOne(query, Message.class);
        return message;
    }

    /**
     * 消息撤销
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public String revocationMessage(Long userId, String publishId) {
        //Integer userIdInt = Convert.toInt(userId);
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
        Update update = new Update();
        update.set("state",HtTotals.PEOPLE_CHECK.getType());
        update.set("userId",userId);
        update.set("updated",System.currentTimeMillis());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Message.class);
        if (updateResult.getModifiedCount()>0){
            return publishId;
        }

        return null;
    }

    /**
     * 消息翻页
     * @param page
     * @param pagesize
     * @param sortProp
     * @param sortOrder
     * @param id
     * @param sd
     * @param ed
     * @param uid
     * @param state
     * @return
     */
    @Override
    public List<Message> getMessagePage(Integer page, Integer pagesize, String sortProp, String sortOrder, String id, Long sd, Long ed, Long uid, Integer state) {

            PageRequest pageRequest =null;

            if ("descending".equals(sortOrder)&&(ObjectUtil.notEqual("-1",sortProp))){//降序"-1".equals(sortProp))
                 pageRequest = PageRequest.of(page-1,pagesize, Sort.by(Sort.Order.desc(sortProp)));
            }else if ("ascending".equals(sortProp)&&ObjectUtil.notEqual("-1",sortProp)){//升序
                 pageRequest = PageRequest.of(page-1,pagesize, Sort.by(Sort.Order.asc(sortProp)));
            }else if (ObjectUtil.notEqual("-1",sortProp)){
                pageRequest = PageRequest.of(page-1,pagesize);
            }

        Query query =new Query();
        Criteria criteria=new Criteria();

        if (state==null||state==0){//审核状态为空

//            query =new Query();

        }else {//审核状态不为空
            criteria.and("state").is(state);
//            criteria.where("state").is(state);

        }

        if (ObjectUtil.notEqual("0",id)){//用户id不为空!(id.equals("0"))

            criteria.and("publishUserId").is(Convert.toInt(id));
        }

        if (sd>0&&ed>0){//开始结束时间不为空

            criteria.andOperator(Criteria.where("createDate").gte(sd),
                    Criteria.where("createDate").lte(ed));

        }

        query.addCriteria(criteria).with(pageRequest);


        List<Message> messageList = mongoTemplate.find(query,Message.class);

        if (CollUtil.isNotEmpty(messageList)){
            return messageList;
        }

        return null;





    }

    /**
     * 修改消息审核状态
     * @param userId
     * @param publishId
     * @param htTotals
     * @return
     */
    private String updateMessageState(Long userId,String publishId,HtTotals htTotals){

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
        Update update = new Update();
        update.set("state",htTotals.getType());
        update.set("userId",userId);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Message.class);
        if (updateResult.getModifiedCount()>0){
            return publishId;
        }

        return null;
    }

    /**
     * 保存消息
     * @param
     * @param
     * @param
     * @return
     */
    public String saveMessage(Publish publish){
/*        Message message =null;
        List<Publish> publishList = mongoTemplate.findAll(Publish.class);
        for (Publish publish1 : publishList) {
            String publishIdx = publish1.getId().toHexString();*/


                //1.封装消息对象
                Message message = new Message();
                message.setCreateDate(publish.getCreated());
                message.setId(ObjectId.get());
                message.setPublishId(publish.getId());
                message.setState(3);
                //message.setUserId(Convert.toInt(userId));
                message.setTopState(1);

                //2.查询动态
                //Publish publish = quanZiApi.queryPublishById(publishIdx);
                message.setPublishUserId(Convert.toInt(publish.getUserId()));

                //3.保存消息
                mongoTemplate.save(message);


        return message.getId().toHexString();

    }

    /**
     * 根据信息状态查询信息表中所有的信息的状态数
     * @return
     */
    public Integer queryAllState(HtTotals htTotals){

        Query query = Query.query(Criteria.where("state").is(htTotals.getType()));
        long count = mongoTemplate.count(query, Message.class);
        return Convert.toInt(count);
    }

    /**
     * 根据用户id查询信息列表(分页)
     * @param uid
     * @param page
     * @param pagesize
     * @param sortProp
     * @param sortOrder
     * @return
     */
    @Override
    public List<Message> findPublishByUid(Long uid, Integer page, Integer pagesize, String sortProp, String sortOrder) {

        /*PageRequest pageRequest =null;

        if ("descending".equals(sortOrder)&&(ObjectUtil.notEqual("-1",sortProp))){//降序"-1".equals(sortProp))
            pageRequest = PageRequest.of(page-1,pagesize, Sort.by(Sort.Order.desc(sortProp)));
        }else if ("ascending".equals(sortProp)&&ObjectUtil.notEqual("-1",sortProp)){//升序
            pageRequest = PageRequest.of(page-1,pagesize, Sort.by(Sort.Order.asc(sortProp)));
        }else if (ObjectUtil.notEqual("-1",sortProp)){
            pageRequest = PageRequest.of(page-1,pagesize);
        }*/



        Query query =Query.query(Criteria.where("publishUserId").is(uid).and("topState").is(HtTopState.UNSTICK.getType()));
        List<Message> messageList = mongoTemplate.find(query, Message.class);

        return messageList;

    }

    public List<Message> findTop(Long uid){
        Query query =Query.query(Criteria.where("publishUserId").is(uid).and("topState").is(HtTopState.STICK.getType()));
        List<Message> messageList = mongoTemplate.find(query, Message.class);
        return messageList;
    }


    /**
     * 根据用户id查询信息数
     * @param uid
     * @return
     */

    public Long countPublishByUid(Long uid){

        Query query =Query.query(Criteria.where("publishUserId").is(uid));
        long count = mongoTemplate.count(query, Message.class);

        return count;

    }




}
